<?php

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\Discount\Repositories\DiscountRepository;
use iBrand\Shop\Server\Resources\CouponsResource;
use iBrand\Component\Discount\Services\DiscountService;
use DNS1D;
use iBrand\Component\User\Models\User;
use iBrand\Common\Controllers\Controller;

class CouponController extends Controller
{
    private $couponRepository;
    private $discountService;
    private $discountRepository;

    public function __construct(
        CouponRepository $couponRepository
        , DiscountService $discountService
        , DiscountRepository $discountRepository
    )
    {
        $this->couponRepository = $couponRepository;
        $this->discountService = $discountService;
        $this->discountRepository = $discountRepository;
    }

    /**
     * 获取优惠券列表
     *
     * @return mixed
     * is_Active 是否有效 0 无效 1有效
     */
    public function getCoupon()
    {
        if (empty(request('is_active')) AND request('is_active') === '') {
            return $this->failed('无效请求,缺少请求参数');
        }

        if (empty(request('user_id')) || !request('user_id')) {
            return $this->failed('无效请求,缺少请求参数');
        }

        $is_active = request('is_active');
        $user_id = request('user_id');
        $limit = request('limit') ? request('limit') : 15;
        if ($is_active == 0) {
            $coupons = $this->couponRepository->findInvalidByUser($user_id);
        } elseif ($is_active == 1) {
            if (request('channel')) {
                $coupons = $this->couponRepository->findActiveByUser($user_id, $limit, request('channel'));
            } else {
                $coupons = $this->couponRepository->findActiveByUser($user_id, $limit, 'shop');
            }
        } else {
            $coupons = $this->couponRepository->findUsedByUser($user_id);
        }

        return $this->paginator($coupons, CouponsResource::class);
    }

    /**
     * 领取优惠券
     */
    public function getCouponConvert()
    {
        if (!request('coupon_code')) {
            return $this->failed('请输入兑换码');
        }

        try {

            $utm_campaign = request('utm_campaign');

            $utm_source = request('utm_source');

            $type = request('type') ? request('type') : 0;

            if (request('agent_code')) {

                if ($this->discountService->CouponIsAgentShare(request('coupon_code'))) {

                    $agent = $this->agentRepository->findWhere(['status' => 1, 'code' => request('agent_code')])->first();

                    if ($agent) {

                        $utm_campaign = 'agent';

                        $utm_source = $agent->id;
                    }
                }
            }

            //$couponConvert = $this->discountService->getCouponConvert(request('coupon_code'), request()->user()->id, $type, $utm_campaign, $utm_source);

            $couponConvert = $this->discountService->getCouponConvert(request('coupon_code'), request()->user()->id, $utm_campaign, $utm_source);

            $couponConvert = $couponConvert ? $couponConvert->toArray() : [];

            return $this->success($couponConvert);
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }

    /**
     * 获取优惠券详细信息
     *
     * @param $couponId
     *
     * @return Response
     */
    public function getCouponDetails($couponId)
    {
        $CouponDetails = $this->couponRepository->getCouponDetails($couponId, request()->user()->id);

        return $this->success($CouponDetails);
    }

    /**
     * 获取可用优惠券数量
     *
     * @return mixed
     */
    public function getCouponNumByUser()
    {
        return $this->success($this->couponRepository->getValidCouponCountByUser(request()->user()->id));
    }

    /**
     * 获取条形码
     *
     * @return Response
     */
    public function getCouponBarCodes()
    {
        $barCode = DNS1D::getBarcodePNG(request('coupon_code'), "EAN13", "4", "100");

        return $this->success(['base64' => 'data:image/png;base64,' . $barCode]);
    }

    /**
     * get coupon discount
     *
     * @param $id
     */
    public function getShareCoupon($id)
    {
        if (!$discount = $this->discountRepository->find($id) OR !$discount->isCouponBased()) {
            return $this->api(null, false, 400, '不存在此优惠券');
        }

        return $this->success($discount);
    }

    /**
     * 领券页面获取优惠券信息
     *
     * @return \Dingo\Api\Http\Response
     */
    public function getCouponByType()
    {
        if (!request('code') AND !request('id')) {
            return $this->failed('参数错误');
        }

        if ($code = request('code')) {
            $discount = $this->discountRepository->findWhere(['code' => $code])->first();
        }
        if ($id = request('id')) {
            $discount = $discount = $this->discountRepository->find($id);
        }

        if (!$discount OR !$discount->isCouponBased()) {
            return $this->failed('不存在此优惠券');
        }

        return $this->success($discount);
    }

    /**
     * 推客优惠券分享页面
     *
     * @param $agent_code
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getAgentCouponView($agent_code)
    {

        $agent = $this->agentRepository->findWhere(['status' => 1, 'code' => $agent_code])->first();

        $coupon = $this->discountRepository->find(request('coupon_id'));

        if (!$agent || !$coupon || $coupon->is_agent_share != 1) {
            abort(404);
        }

        $user = User::find($agent->user_id);

        $scene = request('coupon_id') . '_' . $agent->code;

        return view('server::share.agent_coupon', compact('coupon', 'user', 'scene'));
    }

    /**
     * 批量领取优惠券
     *
     * @return \Dingo\Api\Http\Response
     */
    public function getCouponConvertBatch()
    {
        if (!$discountIds = request('discount_ids')) {
            return $this->failed('请输入兑换码');
        }
        $user = request()->user();
        try {
            foreach ($discountIds as $id) {
                $discount = $this->discountRepository->find($id);
                $this->discountService->getCouponConvert($discount->code, $user->id);
            }

            return $this->success();
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }

}